<template>
  <div>
    <el-table
      @select="handleSelectionChange"
      @select-all="selectAll"
      :max-height="tableMaxHeight"
      v-loading="loading"
      :data="tableParams.rows"
      ref="tableRef"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column
        label="状态"
        prop="name"
        width="55"
        fixed="left"
        align="center"
      >
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>
          <div class="status-icon" v-else-if="scope.row.userState == 2">
            <img
              src="https://shdiditazi.oss-cn-shanghai.aliyuncs.com/image/6ec5b77ded30e5ff51a211dd703a097f.png"
              alt=""
            />
          </div>
          <div v-else class="status-icon flex justifyCenter">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" label="序号" fixed="left">
        <template #default="scope">
          {{
            (formInline.pageIndex - 1) * formInline.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="80" fixed="left">
        <template #default="scope">
          {{ field_format(scope.row, "name") }}
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="120">
        <template #default="scope">
          {{ field_format(scope.row, "mobile") }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号" width="180">
        <template #default="scope">
          {{ field_format(scope.row, "identityCard") }}
        </template>
      </el-table-column>
      <el-table-column label="报名所属" width="150">
        <template #default="scope">
          {{ affiliation_format(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column
        label="所在企业名称"
        min-width="200"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ field_format(scope.row, "enterprise") }}
        </template>
      </el-table-column>
      <el-table-column label="累计工作年限" width="120" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "workYears") }}
        </template>
      </el-table-column>
      <el-table-column label="最高学历" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "education") }}
        </template>
      </el-table-column>
      <el-table-column label="毕业专业" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "graduationMajor") }}
        </template>
      </el-table-column>
      <el-table-column label="就业状态" width="80">
        <template #default="scope">
          {{ field_format(scope.row, "employed_Status") }}
        </template>
      </el-table-column>
      <el-table-column prop="order_Info.price" label="订单价格" width="100">
        <template #default="scope">
          {{ proxy.$utils.formatNumber(scope.row.order_Info.displayPrice) }}
        </template>
      </el-table-column>
      <el-table-column prop="price" label="报名状态" width="120" align="center">
        <template #default="scope">
          <div v-if="scope.row.order_Info.status">
            <el-tag
              type="danger"
              v-if="
                scope.row.order_Info.status == 1 &&
                scope.row.order_Info.rejectMsg
              "
              >已驳回</el-tag
            >
            <el-tag
              v-else
              :color="counter.tagBgColor(scope.row.order_Info.status)"
            >
              <div
                :style="{
                  color: counter.tagColor(scope.row.order_Info.status),
                }"
              >
                {{ status_format(scope.row.order_Info.status) }}
              </div>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="查看凭证"
        width="100"
        fixed="right"
      >
        <template #default="scope">
          <div
            class="button textCenter"
            @click="handleClick(scope.row)"
            v-if="
              [2, 7].includes(scope.row.order_Info.status) &&
              scope.row.order_Info.displayPrice
            "
          >
            下载
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="tableParams['total']"
      :total="tableParams['total']"
      v-model:page="formInline.pageIndex"
      v-model:limit="formInline.pageSize"
      @pagination="getInfo"
    />
  </div>
</template>

<script setup lang="ts">
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
import { onMounted } from "vue";
const counter = useCounterStore();
let props = defineProps(["info"]);
const emit = defineEmits(["fatherMethod"]);

let formInline = ref({
  pageIndex: 1,
  pageSize: 50,
  classId: "",
  keyWords: "",
});
let selectData = ref([]);
let templateUrl = "";
let tableParams = ref({});
let loading = ref(false);
let tabs = ref([
  { name: "待审核", value: 1 },
  { name: "审核未通过", value: 3 },
  { name: "支付尾款", value: 8 },
  { name: "报名成功", value: 2 },
  { name: "优惠减免", value: 10 },
  { name: "已退款", value: 4 },
  { name: "部分退款", value: 9 },
  { name: "已开票", value: 7 },
]);

let tableMaxHeight = computed(() => {
  let hei =
    window.innerHeight -
    84 -
    counter.pageHeight -
    160 -
    counter.classCardHeight;
  return `${hei}px`;
});

onMounted(() => {
  getInfo();
  getTemplateUrl();
});

function handleSelectionChange(e, k) {
  //selectData.value = e;
  if (proxy.$utils.isFieldEqual(e, "_id", k._id)) {
    selectData.value.push(k);
  } else {
    let index = proxy.$utils.findIndexByField(selectData.value, "_id", k._id);
    if (index != -1) selectData.value.splice(index, 1);
  }
  emit("fatherMethod", selectData.value);
}

function setDefaultValue() {
  nextTick(() => {
    selectData.value.forEach((element) => {
      let a = tableParams.value.rows.find((el) => {
        return element._id == el._id; // 注意这里寻找的字段要唯一，示例仅参考
      });
      if (a) proxy.$refs.tableRef.toggleRowSelection(a, true);
    });
  });
}

function selectAll(array) {
  if (array.length) {
    array.forEach((element) => {
      if (proxy.$utils.isFieldEqual(selectData.value, "_id", element._id)) {
      } else {
        selectData.value.push(element);
      }
    });
  } else {
    if (tableParams.value.rows && tableParams.value.rows.length) {
      tableParams.value.rows.forEach((element) => {
        let index = proxy.$utils.findIndexByField(
          selectData.value,
          "_id",
          element._id
        );
        if (index != -1) selectData.value.splice(index, 1);
      });
    }
  }
  //console.log("selectData.value", selectData.value);
  emit("fatherMethod", selectData.value);
}

async function getTemplateUrl() {
  templateUrl = await proxy.$apis.fileTemplate({
    data: { type: "receiptVoucher" },
    type: "downLoad",
  });
}

async function handleClick(row, type = 1) {
  //1=直接下载  2.return下载地址
  if (!templateUrl) return proxy.$utils.showToast("请先上传支付凭证模板", 0);
  await getTemplateUrl();
  let obj = {};
  let { pay_info, out_trade_no, displayPrice } = row.order_Info;
  obj["year"] = proxy.$utils.dateTimeFormateFn(pay_info.pay_time, "year");
  obj["month"] = proxy.$utils.dateTimeFormateFn(pay_info.pay_time, "month");
  obj["day"] = proxy.$utils.dateTimeFormateFn(pay_info.pay_time, "day");
  obj["payeUser"] = row.userName;
  let { courseDuration, name } = await proxy.$apis.course({
    type: "details",
    data: { _id: row.curriculum_id },
  });
  obj["courseDuration"] = courseDuration;
  obj["name"] = name;
  let price = proxy.$utils.numberToChinese(displayPrice);
  obj["displayPrice"] = displayPrice;
  obj["price"] = price;
  obj["out_trade_no"] = out_trade_no;
  let url = await proxy.$apis.classDocExport({
    templateURL: templateUrl,
    data: obj,
    fileName: `${row._id}.docx`,
  });
  if (type == 1) {
    proxy.$utils.downloadImage(url, `${row.userName}支付凭证.docx`);
  } else {
    return {
      url,
      fileName: `${row.userName}支付凭证`,
    };
  }
}

function status_format(e) {
  if (e == 8) {
    return "支付尾款";
  } else if (e == 10) {
    return "报名成功";
  } else {
    for (let index = 0; index < tabs.value.length; index++) {
      const element = tabs.value[index];
      if (element.value == e) return element.name;
    }
  }
}

function affiliation_format(item) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  if (!row.affiliation) return "-";
  if (proxy.$utils.isString(row.affiliation)) {
    return row.affiliation;
  } else if (proxy.$utils.isJsonArray(row.affiliation) == "arr") {
    return row.affiliation.toString() || "-";
  } else {
    return "-";
  }
}

function getGenderByIdCard(item) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  let idCard = row.identityCard;
  if (!idCard || idCard.length !== 18) return "-";
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

function field_format(item, key) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  if (key == "enterprise") return counter.showEnterprise(row, key);
  return row[key];
}

async function getInfo() {
  try {
    loading.value = true;
    if (!props.info._id) return;
    formInline.value.classId = props.info._id;
    formInline.value.keyWords = formInline.value.keyWords.trim();
    tableParams.value = await proxy.$apis.classStudent({
      type: "list",
      data: formInline.value,
    });
    console.log("tableParams.value", tableParams.value);
    setDefaultValue();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

async function exportWord() {
  let arr = [];
  for (let index = 0; index < selectData.value.length; index++) {
    const element = selectData.value[index];
    let { url, fileName } = await handleClick(element, 2);
    arr.push({ path: url, name: fileName });
  }
  proxy.$utils.JSZipDownLoad(arr, "收款凭证导出");
}

defineExpose({ exportWord });
</script>

<style lang="scss" scoped>
.status-icon {
  width: 15px;
  height: 15px;
  margin: auto;
  img {
    width: 100%;
    display: block;
  }
}
.extendedExam {
  color: #e6a23c;
}
</style>
